package it11.Capood.DataLogic;


import it11.Capood.R;
import it11.Capood.GUI.SendingTextActivity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ClipboardManager;
import android.content.ClipboardManager.OnPrimaryClipChangedListener;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

public class ClipListenService extends Service implements OnPrimaryClipChangedListener{
	
	
	private final static String TAG = "clip123";
	private ClipboardManager cm;
	private static ClipListenService service_running = null;


	public static final String PREF_CLIP_SERVICE = "pref_clip_service";


	@Override
	public int onStartCommand(Intent intent,int flags, int startid){
		
		cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
		cm.addPrimaryClipChangedListener(this);
		
		
		
		service_running = this;
		
		Log.i(TAG, "ClipService started!");
		return Service.START_STICKY;		
	}
	
	@Override
	public void onDestroy(){
		service_running = null;
		
		cm.removePrimaryClipChangedListener(this);
		Log.i(TAG, "ClipService stopped");
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	
	@Override
	public void onPrimaryClipChanged() {
		Log.i(TAG,"Clip changed!");
				
		Intent resultInt = new Intent(this, SendingTextActivity.class);
		
		String msg = cm.getPrimaryClip().getItemAt(0).coerceToText(getApplicationContext()).toString();
		
		resultInt.putExtra(SendingTextActivity.EXTRA_TEXT, msg);
		
				
		PendingIntent resultPendInt = PendingIntent.getActivity(getApplicationContext(), 0, resultInt, PendingIntent.FLAG_UPDATE_CURRENT);
		
		NotificationCompat.Builder builder =
				new NotificationCompat.Builder(this)
				.setSmallIcon(R.drawable.capood_icon2)
				.setContentTitle("Capood - Text was copied to Clipboard")
				.setContentText(msg)
				.setContentIntent(resultPendInt)
				.setAutoCancel(true);		

		((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(123, builder.build());
	}

	public static ClipListenService getRunningService() {
		return service_running;
	}
	
	 public static boolean isRunning(){
    	if (service_running != null) {
    		return true;
    	} else {
    		return false;
    	}
    }
}
